package com.lzx.mumianaicodegenerator.core.saver;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.lzx.mumianaicodegenerator.ai.model.enums.CodeGenTypeEnum;
import com.lzx.mumianaicodegenerator.constant.AppConstant;
import com.lzx.mumianaicodegenerator.exception.BusinessException;
import com.lzx.mumianaicodegenerator.exception.ErrorCode;

import java.io.File;
import java.nio.charset.StandardCharsets;

public abstract class CodeFileSaverTemplate <T>{
    // 文件保存根目录
    protected static final String FILE_SAVE_ROOT_DIR = AppConstant.CODE_OUTPUT_ROOT_DIR;
    public final File saveCode(T result,Long appId){
        validateInput(result);
        String baseDirPath = buildUniqueDir(appId);
        saveFiles(result,baseDirPath);
        return new File(baseDirPath);
    }

    protected void validateInput(T result) {
        if (result == null) throw new BusinessException(ErrorCode.SYSTEM_ERROR, "保存文件失败，结果为空");
    }
    protected final String buildUniqueDir(Long appId){
        if (appId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "保存文件失败，appId为空");
        }
        String codeType = getCodeType().getValue();
        String uniqueDirName = StrUtil.format("{}_{}",codeType, appId);
        String dirPath = FILE_SAVE_ROOT_DIR + File.separator + uniqueDirName;
        FileUtil.mkdir(dirPath);
        return dirPath;
    }
    protected final void writeToFile(String dirPath,String fileName,String fileContent){
        if (StrUtil.isBlank(fileContent)) return;
        String filePath = dirPath + File.separator + fileName;
        FileUtil.writeString(fileContent,filePath, StandardCharsets.UTF_8);
    }
    protected abstract CodeGenTypeEnum getCodeType();

    protected abstract void saveFiles(T result,String baseDirPath);
}
